# main_test.py
import os
import pytest
import sys
from datetime import datetime
from pathlib import Path

sys.dont_write_bytecode = True
def run_tests():
    """运行 test 文件夹下的所有测试用例并生成报告"""
    report_dir = "reports"
    html_report = Path(report_dir) / "html" / f"report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.html"
    
    # 创建报告目录
    os.makedirs(html_report.parent, exist_ok=True)
    
    # 定义 pytest 命令参数
    pytest_args = [
        "tests/",  # 测试目录
        "--browser=chrome",
        f"--html={html_report}",
        "-v",
        "-s",
        "--env=staging"
    ]
    
    print(f"运行 pytest 命令: pytest {' '.join(pytest_args)}")
    
    try:
        result = pytest.main(pytest_args)
        if result == 0:
            print("所有测试用例执行成功！")
            print(f"HTML 报告: {html_report}")
        elif result == 1:
            print("部分测试用例失败，但仍生成报告")
            print(f"HTML 报告: {html_report}")
        else:
            print(f"测试执行失败，返回码: {result}")
        return result
    
    except Exception as e:
        print(f"测试运行出错: {str(e)}")
        return 1

if __name__ == "__main__":
    exit_code = run_tests()
    sys.exit(exit_code)